/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package marketrmi;


import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author yann
 */
public class Wish extends UnicastRemoteObject implements marketrmi.WishInter {

    private ItemInter item;
    private int wishPrice;
    private AccountClientInter refAccountWisher;
    private String wisherName;
    private static final String tableName = "wish";
    private String datasource = "marketbdd";
    private String dbms= "mysql";
    private Statement sqlStatement;

    public Wish(ItemInter itemRef, int wishPriceMax, AccountClientInter refAccountWisher) throws RemoteException, Rejected {
        try {
            this.refAccountWisher = refAccountWisher;
            wisherName = refAccountWisher.getClientName();
            String clientName = refAccountWisher.getClientName();
            this.item = itemRef;
            this.wishPrice = wishPriceMax;
            createDatasource();
            boolean present = false;
            try{
                int idItem = itemRef.getId();
                String nameWisher = refAccountWisher.getClientName();
                ResultSet result = null;
                result = sqlStatement.executeQuery("SELECT * FROM wish WHERE idItem='"+ idItem +"' AND wisherName='"+ nameWisher+"'");
                if( result.next()){
                    present = true;
                }
            } catch (RemoteException ex) {
                Logger.getLogger(Item.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
            Logger.getLogger(Item.class.getName()).log(Level.SEVERE, null, ex);
            }
            if( !present){
                int rows = sqlStatement.executeUpdate("INSERT INTO " + tableName + " VALUES ("+itemRef.getId()+", '"+clientName+"', "+wishPriceMax+")");
                    if (rows == 1) {
                        System.out.println("wish has been created for item " + item.getItemName());
                    } else {
                        throw new Rejected("cannot create wish in the DBB");
                    }
            }
        } catch (SQLException ex) {
            Logger.getLogger(Wish.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
     private synchronized void createDatasource() {
        try {
            Connection connection = getConnection();
            System.out.println("connected to the BDD");
            sqlStatement = connection.createStatement();
            boolean exist = false;

            DatabaseMetaData dbm = connection.getMetaData();
            for (ResultSet rs = dbm.getTables(null, null, "wish", null); rs.next();) {
                exist = true;
                rs.close();
                System.out.println("the table already exists");
                break;
            }
            if (!exist) {
                System.out.println("create a new table named wish");
                sqlStatement.executeUpdate("CREATE TABLE wish (id int PRIMARY KEY,wisherName, offer float)");
            }
        } catch (ClassNotFoundException ex) {
            
        } catch (SQLException ex) {
            
        }
    }

    private synchronized Connection getConnection() throws ClassNotFoundException, SQLException {
        if (dbms.equalsIgnoreCase("mysql")) {
            Class.forName("com.mysql.jdbc.Driver");
            return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/" + datasource, "root", "");
        } else {
            return null;
        }
    }

    @Override
    public synchronized void setItem(ItemInter item) {
        this.item = item;
    }

    @Override
    public synchronized void setWishPrice(int wishPrice) {
        this.wishPrice = wishPrice;
    }

    @Override
    public synchronized ItemInter getItem() {
        return item;
    }

    @Override
    public synchronized int getWishPrice() {
        return wishPrice;
    }

    @Override
    public synchronized String toString() {
        String ret = "You have a wish for the item: " + this.item + " at a price of: " + this.wishPrice + " Kr";
        return ret;
    }

    @Override
    public synchronized AccountClientInter getRefAccountWisher() {
        return refAccountWisher;
    }

    @Override
    public synchronized void setRefAccountWisher(AccountClientInter refAccountWisher) {
        this.refAccountWisher = refAccountWisher;
    }

    @Override
    public synchronized void deleteAllBuyerWishes() throws RemoteException {
        try {
            sqlStatement.executeUpdate("DELETE FROM "+tableName+" WHERE wisherName='"+wisherName+"'");
        } catch (SQLException ex) {
            Logger.getLogger(Wish.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("unable de delete the wish");
        }
    }
    
    
    
}
